<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Ttc\Controller;
// use User\Api\UserApi;

/**
 * 土特产用户
 */

class PublicController extends \Think\Controller
{

  public function index()
  {
      // $this->meta_title = '上传图片';
      $this->display('index');
  }

  /**
   * 土特产用户登录/注册
   */
  public function login(){
        $data = inputJson();

        // $data['mobile'] = '15919574000';
        // $data['verify'] = '490921';
        // $data['msm_verify'] = '490921';

        // $data['phpsid'] = 'rhjsjsjsj';

        $cdata['phpsid'] = $data['phpsid'];
        $cdata['code'] = $data['verify'];

        /* 检测验证码 TODO: */
        if(!check_verify($cdata,1,1)){
            abnormalOutputJson(['info'=>'验证码输入错误！','type'=>1]);
        }

        /* 检测手机号 */
        if (!preg_match("/^1[34578]\d{9}$/", $data['mobile'])) {
          abnormalOutputJson(['info' => '手机格式错误','type'=>2]);
        }


        /* 检测短信验证码 */
        $sms_log_model = D('SmsLog');
        $res = $sms_log_model->getSmsInfo(array('log_phone' => $data['mobile']));
        if ($res === false) {
          errorOutputJson('b' . __LINE__);
        } elseif (empty($res)) {
          errorOutputJson('b' . __LINE__);
        } else {
          // var_dump($res['log_captcha']);
          // var_dump($data['msm_verify']);
          if (($res['log_captcha'] != $data['msm_verify']) || ($res['is_use'] == 1)) {
            // if(($res['log_captcha'] != $data['msm_verify'])){
            abnormalOutputJson(['info' => '短信验证码错误！','type'=>3]);
          }
          /* 检测验证码有没有过期 30分钟过期*/
          if ((time() - $res['add_time']) > 60 * 30) {
            abnormalOutputJson(['info' => '验证码已过期，请重新获取！','type'=>3]);
          }

          //判断是登录还是注册
          $TtcMember = D('TtcMember');
          $res = $TtcMember->getMemberInfo(array('mobile' => $data['mobile']));
          if ($res === false) {
            errorOutputJson('b' . __LINE__);
          } elseif (empty($res)) {
            //注册
            $mem_data['mobile'] = $data['mobile'];
            $mem_data['session_id'] = session_id();

            $TtcMember->sx_data = $mem_data;
            $res = $TtcMember->addMember();
            if (isset($res['info'])) {
              abnormalOutputJson(['info' => $res['info'],'type'=>2]);
            } elseif (!$res) {
              errorOutputJson('b' . __LINE__);
            } else {
              //修改验证码状态
              $sms['log_phone'] = $data['mobile'];
              $sms['is_use'] = 1;
              $SmsLog = D('SmsLog');
              $res = $SmsLog->saveSms($sms);

              successOutputJson($mem_data['session_id']);
            }
            
          } else {
            //登录

            //修改登录信息
            $mem_data['id'] = $res['id'];


            $TtcMember->sx_data = $mem_data;
            $res = $TtcMember->saveMember();
            if ($res === false) {
              errorOutputJson('b' . __LINE__);
            } else {
              //查session_id
              $condition = array('id' => $mem_data['id']);
              $field = 'session_id';
              $res = D('TtcMember')->getMemberInfo($condition, $field);
              if (!$res) {
                errorOutputJson('b' . __LINE__);
              } else {
                $session_id = $res['session_id'];

                //修改验证码状态
                $sms['log_phone'] = $data['mobile'];
                $sms['is_use'] = 1;
                $SmsLog = D('SmsLog');
                $res = $SmsLog->saveSms($sms);

                successOutputJson($session_id);

              }

            }
          }
        }

  }

  /* 文字验证码 */
  public function verifyInit()
  {
    $data['session_id'] = session_id();
    $VerifLog = D('VerifLog');
    $VerifLog->sx_data = $data;
    $res = $VerifLog->addVerif();
    if ($res === false) {
      errorOutputJson('b' . __LINE__);
    } else {
      successOutputJson($data['session_id']);
    }

  }

  /* 文字验证码 */
  public function verify()
  {
    $verify = new \Think\Verify();
    $verify->fontSize = 50;
    $verify->length = 4;
    $verify->imageW = 400;
    $verify->imageH = 110;
    $verify->codeSet = '0123456789';
    $verify->useCurve = false;
    $verify->sxentry(1);
  }

  /* 验证文字验证码 */
  public function check_verify()
  {
    // $data = inputJson();
    $data = inputJson();
    // $data['phpsid'] = 'gb3ad25lu6gn1o9jp33ao9tm76';
    // $data['code'] = '1234';
    if (!check_verify($data)) {
      abnormalOutputJson(['info' => '验证码错误']);
    } else {
      successOutputJson();

    }

  }

  /* 是否登录 */
  public function is_login()
  {
    // $data = inputJson();
    $data = inputJson();

    // $data['phpsid'] = 'bqodcvt6gbl9k700ql2afqifr4';

    $res = is_login($data['phpsid']);

    if ($res) {
      //如果已经登录了判断是否发布过土特产(前端发布过跳到列表页)
      $member_id =get_userId($data['phpsid']);//用户id
      $goods = D('TtcGoods')->getOneGoods(array('member_id'=>$member_id));
      if($goods === false){
        errorOutputJson('b' . __LINE__);
      }if(empty($goods)){
        successOutputJson(null,['has_goods'=>0]);
      }else{
        successOutputJson(null,['has_goods'=>1]);
      }
    } else {
      abnormalOutputJson(['info' => '请先登录']);

    }
  }

  /* 是否实名认证 */
  public function is_identity()
  {
        $data = inputJson();
        // $data['phpsid'] = 'bqodcvt6gbl9k700ql2afqifr4';

        //是否登录
        $res = is_login($data['phpsid']);
        if (!$res) {
          abnormalOutputJson(['info' => '请先登录', 'type' => 1]);
        }
        //查询实名状态
        $TtcMember = D('TtcMember');
        $condition = array('session_id' => $data['phpsid']);
        $filed = 'is_identity';
        $res = $TtcMember->getMemberInfo($condition, $filed);

        if (!$res) {
              errorOutputJson('b' . __LINE__);
        } else {
              if ($res['is_identity'] == 0) {
                  abnormalOutputJson(['info' => '请先实名', 'type' => 2]);
              } else {
                  //如果已经实名了判断是否发布过土特产(前端发布过跳到列表页)
                  $member_id =get_userId($data['phpsid']);//用户id
                  $goods = D('TtcGoods')->getOneGoods(array('member_id'=>$member_id));
                  if($goods === false){
                      errorOutputJson('b' . __LINE__);
                  }if(empty($goods)){
                      successOutputJson(null,['has_goods'=>0]);
                  }else{
                      successOutputJson(null,['has_goods'=>1]);
                  }
              }
        }

  }

  /**
   * 发送手机验证码
   * @param string $phone 手机号
   * @param string $log_type 短信类型:1为注册,2为登录
   * @return array
   */
  public function sendCaptcha()
  {
    $data = inputJson();

    //假数据
    // $data['phone'] = '18826075508';

    $phone = $data['phone'];
    //查询是注册还是登陆(区分验证码内容)
    $model_member = D('TtcMember');
    $is_member = $model_member->getMemberInfo(array('mobile' => $phone));
    if (!empty($is_member)) {
      //登录
      $log_type = 2;
    } else {
      //注册
      $log_type = 1;
    }

    $model_sms_log = D('SmsLog');
    $state = true;
    $msg = '手机验证码发送成功';

    //查询是否存在同一手机号同一类型记录,60秒内不能发送多次
    $condition = array();
    $condition['log_phone'] = $phone;
    $condition['log_type'] = $log_type;
    $sms_log = $model_sms_log->getSmsInfo($condition);
    if (!empty($sms_log) && ($sms_log['add_time'] > (time() - C('SEND_SMSCODE')['DEFAULT_CONNECT_SMS_TIME']))) {//同一手机号IP[n]秒内只能发一条短信
      $state = false;
      $msg = '同一手机号' . C('SEND_SMSCODE')['DEFAULT_CONNECT_SMS_TIME'] . '秒内，请勿多次获取验证码！';
    }

    if ($state == true) {
      $log_array = array();
      $model_member = D('TtcMember');
      $member = $model_member->getMemberInfo(array('mobile' => $phone));

      $captcha = rand(100000, 999999);

      $log_msg = '您于' . date("Y-m-d");
      //            $log_msg = '【'.C('site_name').'】您于'.date("Y-m-d");
      switch ($log_type) {
        case '1':
          if (!empty($member)) {//检查手机号是否已被注册
              $state = false;
              $msg = '当前手机号已被注册，请更换其他号码。';
          }else{
            $log_msg .= '申请注册会员，验证码：' . $captcha . '。';
          }
          break;
        case '2':
          if (empty($member)) {//检查手机号是否已绑定会员
            $state = false;
            $msg = '当前手机号未注册，请检查号码是否正确。';
          }else{
            $log_msg .= '申请登录，验证码：' . $captcha . '。';
          }
          break;
        default:
          $state = false;
          $msg = '参数错误';
          break;
      }
      if ($state == true) {
        $result = $this->sms_verify($phone, $log_msg);
        if ($result == 0) {
          $log_array['log_phone'] = $phone;
          $log_array['log_captcha'] = $captcha;
          $log_array['log_ip'] = getIp();
          $log_array['log_msg'] = $log_msg;
          $log_array['log_type'] = $log_type;
          $log_array['add_time'] = time();
          $model_sms_log->addSms($log_array);
          successOutputJson();

        } else {
          abnormalOutputJson(['info'=>'手机短信发送失败']);
        }
      }else{
          abnormalOutputJson(['info'=>$msg]);
      }
    }else{
      abnormalOutputJson(['info'=>$msg]);
    }
  }

  public function sms_verify($receiver, $body)
  {
    $post_data = array();
    $post_data['account'] = iconv('GB2312', 'GB2312', "daxuejia");
    $post_data['pswd'] = iconv('GB2312', 'GB2312', "Tch123456");
    $post_data['mobile'] = $receiver;
    $post_data['msg'] = mb_convert_encoding("$body", 'UTF-8', 'auto');
    $post_data['needstatus'] = 'true';
    $url = 'http://222.73.117.158/msg/HttpBatchSendSM';
    $o = "";
    foreach ($post_data as $k => $v) {
      $o .= "$k=" . urlencode($v) . "&";
    }
    $post_data = substr($o, 0, -1);
    $url = $url . '?' . $post_data;

    $result = file_get_contents($url);
    $result = str_replace("\n", ',', $result);
    $msgid = explode(',', $result);
    //        $msgid = (string)$msgid[2];
    return $msgid[1];
  }

  /* 初始化令牌 */
  public function TokenInit()
  {
      $data = inputJson();
      // $data['phpsid'] = 'bqodcvt6gbl9k700ql2afqifr4';

      //是否登录
      $res = is_login($data['phpsid']);
      if(!$res){
          abnormalOutputJson(['info'=>'请先登录']);
      }
      //生成Token
      $data['token'] = gencode();
      //存在session_id则修改，否则增加
      $data['session_id'] = $data['phpsid'];
      $TokenLog = D('TokenLog');
      $res = $TokenLog->getTokenInfo(array('session_id'=>$data['phpsid']));
      if(empty($res)){
          $data['atime'] = $data['utime'] = time();
          $res = $TokenLog->add($data);
          if(!$res){
              errorOutputJson('b' . __LINE__);
          }
      }else{
          $data['utime'] = time();
          $res = $TokenLog->saveToken($data);
      }
      if ($res === false) {
          errorOutputJson('b' . __LINE__);
      } else {
          successOutputJson($data['token']);
      }
  }
  /* 检查令牌Token */
  public function validataToken($token,$session_id){
      //查询记录表有无这条记录
      $TokenLog = D('TokenLog');
      $res = $TokenLog->getTokenInfo(array('session_id'=>$session_id));
      if(empty($res)){
          return -2;//没有初始化令牌
      }else{
          if($res['token'] === $token){
              //修改数据库token值,接口完成调用后再返还给前端
              $data['token'] = gencode();
              $data['session_id'] = $session_id;
              $data['utime'] = time();
              $res = $TokenLog->saveToken($data);
              if($res === false){
                  return -3;//数据库级别错误
              }else{
                  return $data['token'];
              }
          }else{
              return -1;//请求太快
          }
      }
                
  }

}
